package cn.trycat.config;

import cn.trycat.field.Abc;
import cn.trycat.field.Foo;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.Map;

public class YmlConfigUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext = null;

    private static  String url =null;

    public YmlConfigUtil() {
    }

    public static String getConfigByKey(String key) throws JsonProcessingException {
        if (url ==null){
            YmlConfig ymlConfig = applicationContext.getBean(YmlConfig.class);
            url = ymlConfig.getUrl();
        }
        return url;
    }


    public static void updataUrl () {
        System.out.println("============"+Abc.class.getAnnotation(Foo.class).value());

        Foo foo = Abc.class.getAnnotation(Foo.class);

        System.out.println("4444444444==="+foo.value());
        System.out.println("4444444444==="+foo.count());

        InvocationHandler h = Proxy.getInvocationHandler(foo);

        try {
            Field hField = h.getClass().getDeclaredField("memberValues");
            hField.setAccessible(true);
            System.out.println("1111111==="+hField.getName());

            Map memberValues = (Map) hField.get(h);

            memberValues.put("value", "BBB");
            memberValues.put("count", 444);

            String value = foo.value();
            int count = foo.count();

            System.out.println("555555555555555555==="+value);
            System.out.println("555555555555555555==="+getConfigByKey("key"));


        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(YmlConfigUtil.applicationContext == null){
            YmlConfigUtil.applicationContext  = applicationContext;
        }
    }
}